package com.open.party.cloud.viewModel;

import android.app.Activity
import android.widget.TextView
import cn.android.x.model.data.AppPageData
import cn.android.x.model.data.ResultInfo
import com.open.party.cloud.ServerConfig
import com.open.party.cloud.model.FileEntity
import com.open.party.cloud.model.JiFenBean
import com.open.party.cloud.model.QueryFileEntity
import com.open.party.cloud.model.data.Api
import com.sinothk.rxretrofit.RxRetrofit
import com.sinothk.rxretrofit.callback.DownloadCallback
import com.sinothk.rxretrofit.param.RetrofitParam
import org.greenrobot.eventbus.EventBus
import rx.Subscriber
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import java.io.File
import java.util.ArrayList
import java.util.concurrent.Executors


class FileViewModel {

    fun uploadFile(bizId: String, bizType: String, filePath: String) {

        RxRetrofit.init(ServerConfig.SERVER_URL, ServerConfig.getHeader())
            .create(Api::class.java)
            .uploadFile(bizId, bizType, "", RetrofitParam.createFileParam("file", File(filePath)))
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Subscriber<ResultInfo<FileEntity>>() {

                override fun onCompleted() {
                }

                override fun onError(e: Throwable) {
                    val result = ResultInfo<FileEntity>(ResultInfo.ERROR, ResultInfo.getErrorMsg(e.message))
                    result.eventType = "uploadFile"
                    EventBus.getDefault().post(result)
                }

                override fun onNext(result: ResultInfo<FileEntity>) {
                    result.eventType = "uploadFile"
                    EventBus.getDefault().post(result)
                }
            })
    }

    fun downLoadFile(activity: Activity, path: String, url: String, loadingTv: TextView) {
        // http://58.16.181.23:10086/2020/06/4a7f8637-e4ea-4e41-a1de-6d641508c089.jpg?attname=tim%E5%97%AF%E5%97%AFvg.jpg

        val index = url.indexOf('/', 10) + 1

        if (index > 0) {

            val baseUrl = url.substring(0, index)
            val contentUrl = url.substring(index)

            try {
                RxRetrofit
                    .init(baseUrl, Executors.newSingleThreadExecutor())
                    .create(Api::class.java)
                    .download(contentUrl)
                    .enqueue(object : DownloadCallback(activity, path) {

                        override fun onStart() {
                            loadingTv.text = "开始下载"
                        }

                        override fun onFinish(path: String?) {
                            loadingTv.text = "已下载"
                        }

                        override fun onFail(errorInfo: String?) {
                            loadingTv.text = "下载失败"
                        }

                        override fun onProgress(currSize: Long, totalSize: Long, progress: Int) {
                            loadingTv.text = "$progress%"
                        }
                    })
            } catch (e: Exception) {
                if (e == null) {

                }
            }
        }
    }

    /**
     * 上传附件
     */
    fun uploadFileForMany(bizId: String, bizType: String, id: String, file: File) {

        RxRetrofit.init(ServerConfig.SERVER_URL, ServerConfig.getHeader())
            .create(Api::class.java)
            .uploadFile(bizId, bizType, id, RetrofitParam.createFileParam("file", file))
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Subscriber<ResultInfo<FileEntity>>() {

                override fun onCompleted() {
                }

                override fun onError(e: Throwable) {
                    val result = ResultInfo<FileEntity>(ResultInfo.ERROR, ResultInfo.getErrorMsg(e.message))
                    result.eventType = "uploadFileForMany"
                    result.msg = id
                    EventBus.getDefault().post(result)
                }

                override fun onNext(result: ResultInfo<FileEntity>) {
                    result.eventType = "uploadFileForMany"
                    result.msg = id
                    EventBus.getDefault().post(result)
                }
            })
    }

    /**
     * 查询附件
     */
    fun queryFile(bizIds: Array<String>, bizTypes: Array<String>) {
        queryFile(bizIds, bizTypes, true)
    }

    /**
     * 查询附件
     */
    private fun queryFile(bizIds: Array<String>, bizTypes: Array<String>, isShowLoading: Boolean) {

        RxRetrofit.init(ServerConfig.SERVER_URL, ServerConfig.getHeader())
            .create(Api::class.java)
            .queryFile(bizIds, bizTypes)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Subscriber<ResultInfo<ArrayList<QueryFileEntity>>>() {

                override fun onCompleted() {
                }

                override fun onError(e: Throwable) {
                    val result = ResultInfo<FileEntity>(ResultInfo.ERROR, ResultInfo.getErrorMsg(e.message))
                    result.eventType = "queryFile"
                    EventBus.getDefault().post(result)
                }

                override fun onNext(resultData: ResultInfo<ArrayList<QueryFileEntity>>) {
                    resultData.eventType = "queryFile"
                    EventBus.getDefault().post(resultData)
                }
            })
    }
}
